package com.example.sonny.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.sonny.Constraint;
import com.example.sonny.bean.BookItem;
import com.example.sonny.bean.PageBean;
import com.example.sonny.dutest.R;
import com.example.sonny.dutest.SingleBookActivity;
import com.example.sonny.dutest.demoData;
import com.example.sonny.util.AsyncHttpClientUtil;
import com.example.sonny.util.adapter.BookListAdapter;

import java.util.ArrayList;
import java.util.List;

import com.loopj.android.http.*;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Large screen devices (such as tablets) are supported by replacing the ListView
 * with a GridView.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener}
 * interface.
 */
public class bookListFragment extends Fragment implements AbsListView.OnItemClickListener,View.OnClickListener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";

    // TODO: Rename and change types of parameters
    private String mParam1;

    private OnFragmentInteractionListener mListener;

    /**
     * The fragment's ListView/GridView.
     */
    private AbsListView mListView;
    private Button test_btn;

    private BookListAdapter mAdapter;

    private ArrayList<BookItem> books;
    private BookItem book;
    private PageBean page;

    private SharedPreferences prefs;
    private SharedPreferences prefs1;
    private SharedPreferences prefs2;
    private String prefName = "spinner_value";
    private String prefName1 = "spinner_value1";
    private String prefName2 = "spinner_value2";
    int id=0;
    int id1=0;
    int id2=0;
    // TODO: Rename and change types of parameters
    public static bookListFragment newInstance(int param1) {
        bookListFragment fragment = new bookListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public bookListFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        if (getArguments() != null) {
            mParam1 = Integer.toString(getArguments().getInt(ARG_PARAM1));
        }

        books = new ArrayList<BookItem>();
        page = new PageBean();
        getData();
       // testApi();
      //  getBookJob(page.getPage_index() + 1);






    }

    private void getData() {
        demoData demo = new demoData();
        demo.initData();
        books = demo.getBooks();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book, container, false);

        // Set the adapter
        mListView = (AbsListView) view.findViewById(android.R.id.list);
       /* test_btn = (Button)view.findViewById(R.id.test_btn);
        test_btn.setOnClickListener(this);*/

        mListView.setOnItemClickListener(this);
        //TODO Just for demo
        mAdapter = new BookListAdapter(getActivity(),books);
        ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);

        final List<String> list=new ArrayList<String>();
        list.add("朝晖校区");
        list.add("屏峰校区");
        list.add("之江校区");
        final List<String> list1=new ArrayList<String>();
        list1.add("计算机学院");
        list1.add("人文学院");
        list1.add("健行学院");
        final List<String> list2=new ArrayList<String>();
        list2.add("软件工程");
        list2.add("播音主持");
        list2.add("自动化");

        final Spinner sp=(Spinner) view.findViewById(R.id.spinner1);
        final Spinner sp1=(Spinner) view.findViewById(R.id.spinner2);
        final Spinner sp2=(Spinner) view.findViewById(R.id.spinner3);
        ArrayAdapter<String> adp= new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1,list);
        ArrayAdapter<String> adp1= new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1,list1);
        ArrayAdapter<String> adp2= new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1,list2);
        adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        adp2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(adp);
        sp1.setAdapter(adp1);
        sp2.setAdapter(adp2);

        prefs = getActivity().getSharedPreferences(prefName, getActivity().MODE_PRIVATE);
        prefs1 = getActivity().getSharedPreferences(prefName1, getActivity().MODE_PRIVATE);
        prefs2 = getActivity().getSharedPreferences(prefName2, getActivity().MODE_PRIVATE);
        id=prefs.getInt("last_val",0);
        id1=prefs1.getInt("last_val",0);
        id2=prefs2.getInt("last_val",0);
        sp.setSelection(id);
        sp1.setSelection(id1);
        sp2.setSelection(id2);

        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0,
                                       View arg1,int pos, long arg3) {

                prefs = getActivity().getSharedPreferences(prefName, getActivity().MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                //---save the values in the EditText view to preferences---
                editor.putInt("last_val", pos);

                editor.commit();


            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
        sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0,
                                       View arg1,int pos, long arg3) {

                prefs1 = getActivity().getSharedPreferences(prefName1, getActivity().MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs1.edit();
                //---save the values in the EditText view to preferences---
                editor.putInt("last_val", pos);

                editor.commit();


            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
        sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0,
                                       View arg1,int pos, long arg3) {

                prefs2 = getActivity().getSharedPreferences(prefName2, getActivity().MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs2.edit();
                //---save the values in the EditText view to preferences---
                editor.putInt("last_val", pos);

                editor.commit();


            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
        return view;
    }

    /*@Override
    temp
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            ((MenuActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_PARAM1));
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }*/

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (null != mListener) {
            // Notify the active callbacks interface (the activity, if the
            // fragment is attached to one) that an item has been selected.
           // mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("book",books.get(position));
        intent.putExtras(bundle);
        intent.setClass(getActivity(), SingleBookActivity.class);
        startActivity(intent);
        //TODO set proper get bundle methods in SingleBookActivity
    }

    /**
     * The default content for this Fragment has a TextView that is shown when
     * the list is empty. If you would like to change the text, call this method
     * to supply the text it should use.
     */
    public void setEmptyText(CharSequence emptyText) {
        View emptyView = mListView.getEmptyView();

        if (emptyView instanceof TextView) {
            ((TextView) emptyView).setText(emptyText);
        }
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(String id);
    }


    private void getBookJob(int p){
        AsyncHttpClient client = AsyncHttpClientUtil.getInstence();
        String action = "api/allbook";
        RequestParams requestParams = new RequestParams();
        requestParams.add("page",Integer.toString(p));
        client.get(Constraint.API_URL + action, requestParams, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    JSONObject page_obj= response.getJSONObject("page");
                    page.setPage_index(page_obj.getInt("page_index"));
                    page.setHas_next(page_obj.getBoolean("has_next"));
                    page.setHas_previous(page_obj.getBoolean("has_previous"));
                    page.setItem_count(page_obj.getInt("item_count"));
                    page.setPage_count(page_obj.getInt("page_count"));
                    if(page.getPage_index()==1){
                        books.clear();
                    }
                    JSONArray array = response.getJSONArray("books");
                    for(int i=0;i<array.length();i++){
                        book =new BookItem();
                        book.setName(array.getJSONObject(i).getString("name"));
                        book.setCreated_at(Double.parseDouble(array.getJSONObject(i).getString("created_at")));
                        book.setId(array.getJSONObject(i).getString("id"));
                        book.setImgUrl(array.getJSONObject(i).getString("imgUrl"));
                        book.setIntro(array.getJSONObject(i).getString("intro"));
                        book.setLend_id(array.getJSONObject(i).getString("lend_id"));
                        book.setState(Integer.parseInt(array.getJSONObject(i).getString("state")));
                        book.setUser_id(array.getJSONObject(i).getString("user_id"));
                        book.setUser_image(array.getJSONObject(i).getString("user_image"));
                        book.setUser_name(array.getJSONObject(i).getString("user_name"));
                        books.add(book);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mAdapter = new BookListAdapter(getActivity(),books);

                ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
                // Set OnItemClickListener so we can be notified on item clicks


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                Log.e("exbook error",Integer.toString(statusCode));
            }
        });
    }



}
